import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { App } from "vue";
import store from "../store";
import Cookies from "js-cookie";
import { getAdminInfoApi } from "../request/api";
const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/login/login.vue')
    },
    // {
    //     path: '/homepage',
    //     name: 'homepage',
    //     component: () => import('../views/homepage/homepage.vue')
    // },
]

const router = createRouter({
    history: createWebHashHistory(),
    // 路由配置
    routes
})
// 根据getters里面的菜单数据生成路由规则
const getRouter = () => {
    const menus = store.getters.getNewMenus
    // const newRoutes: RouteRecordRaw[] = []
    // 循环菜单对象
    for (let key in menus) {
        const newRoute: RouteRecordRaw = {
            path: '/' + menus[key].name,
            name: menus[key].name,
            component: () => import('../views/homepage/homepage.vue'),
            redirect: '/' + menus[key].name + '/' + menus[key].children[0].name,
            children: []
        };
        for (let i = 0; i < menus[key].children.length; i++) {
            newRoute.children?.push({
                path: menus[key].children[i].name,
                name: menus[key].children[i].name,
                component: () => import(`../views/${menus[key].name}/${menus[key].children[i].name}.vue`)
            })
        }
        // 动态添加路由规则
        router.addRoute(newRoute)
    }
    // 动态添加首页
    router.addRoute({
        path: '/',
        name: 'homepage',
        component: () => import('../views/homepage/homepage.vue'),
        redirect: '/index',
        children: [
            {
                path: 'index',
                name: 'index',
                component: () => import('../views/index/index.vue')
            }
        ]
    })
}

// 前置路由守卫
router.beforeEach((to, from, next) => {
    // token存在并且menus里面为空数组
    const token = Cookies.get('token')
    if (token && store.state.menus.length == 0) {
        console.log('刷新后,menus为空,重新获取数据');
        store.dispatch('getAdminInfo').then(() => {
            getRouter()
            next(to)
        })
    } else if (token && store.state.menus.length !== 0 && from.path === '/login' && to.path === '/homepage') {
        getRouter()
        next('index')
    } else if (!token && to.path !== '/login') {
        next('/login')
    } else if (token && to.path == '/login') {
        next(from)
    } else {
        next()
    }
})

export const initRouter = (app: App<Element>) => {
    app.use(router)
}